package com.aaa.tars.service.impl;

import com.aaa.tars.dao.VisitorsDao;
import com.aaa.tars.entity.Visitors;
import com.aaa.tars.service.CodesService;
import com.aaa.tars.service.VisitorsService;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.PasswordEncoderUtil;
import com.aaa.tars.util.Result;
import com.aaa.tars.util.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @FileName: VisitorsServiceImpl
 * @Description: 游客服务实现类
 * @CreateTime: 2025/9/12 16:52
 * @Version: 17
 */
@Service
@Transactional
public class VisitorsServiceImpl implements VisitorsService {

    @Autowired
    private VisitorsDao visitorsDao;

    @Autowired
    private CodesService codesService;
    @Override
//    @Transactional
    public boolean register(Visitors visitors, String verificationCode) {
        // 验证手机验证码
        if (!codesService.verifyCode(visitors.getPhoneNumber(), verificationCode)) {
            return false;
        }

        // 检查手机号是否已经注册
        if (visitorsDao.findVisitorById(visitors.getPhoneNumber()) != null) {
            return false;
        }

        // 加密密码
        String encodedPassword = PasswordEncoderUtil.encode(visitors.getPassword());
        visitors.setPassword(encodedPassword);

        // 生成并设置盐值
        String salt = PasswordEncoderUtil.generateSalt();
        visitors.setSalt(salt);

        // 设置创建时间和更新时间
        Date now = new Date();
        visitors.setCreateTime(now);
        visitors.setUpdateTime(now);

        // 保存用户信息
        return visitorsDao.addVisitor(visitors) > 0;
    }

    @Override
    public Visitors login(String phoneNumber, String password) {
        // 根据手机号查找游客
        Visitors visitors = visitorsDao.findVisitorById(phoneNumber);

        // 验证密码
        if (visitors != null && PasswordEncoderUtil.matches(password, visitors.getPassword())) {
            return visitors;
        }
        return null;
    }

    @Override
    public Visitors findByPhoneNumber(String phoneNumber) {
        return visitorsDao.findVisitorById(phoneNumber);
    }

    @Override
    public int updata(Visitors visitors) {
        // 如果密码被修改，重新加密
        if (visitors.getPassword() != null && !visitors.getPassword().isEmpty()) {
            String encodedPassword = PasswordEncoderUtil.encode(visitors.getPassword());
            visitors.setPassword(encodedPassword);

            // 重新生成盐值
            String newSalt = PasswordEncoderUtil.generateSalt();
            visitors.setSalt(newSalt);
        }

        visitors.setUpdateTime(new Date());
        return visitorsDao.updateVisitor(visitors);
    }




    @Override
    public Visitors queryById(Integer visitorId) {
        return visitorsDao.queryById(visitorId);
    }

    @Override
    public PageInfo queryByPage(Page<Visitors> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo == null || pageNo == 0 || pageSize == null || pageSize == 0) {
            throw new IllegalArgumentException("非法参数异常");
        }
        PageHelper.startPage(pageNo, pageSize);
        Visitors data = page.getData();
        return new PageInfo(visitorsDao.queryAll(data));
    }

    @Override
    public int add(Visitors visitors) {
        visitors.setCreateTime(new Date());
        visitors.setUpdateTime(new Date());
        return visitorsDao.add(visitors);
    }

    @Override
    public int update(Visitors visitors) {
        visitors.setUpdateTime(new Date());
        return visitorsDao.update(visitors);
    }

    @Override
    public int deleteById(Integer visitorId) {
        return visitorsDao.deleteById(visitorId);
    }
    /**
     * 上传游客头像
     * @param file 上传的文件
     * @param visitorId 游客ID
     * @return 上传结果和文件路径
     */
    @Override
    public Result uploadAvatar(MultipartFile file, Integer visitorId) {
        if (file.isEmpty()) {
            return ResultUtil.error("上传文件为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType) && !"image/gif".equals(contentType)) {
            return ResultUtil.error("只允许上传JPG/PNG/GIF格式的图片");
        }

        // 检查文件大小（最大10MB）
        long size = file.getSize();
        if (size > 10 * 1024 * 1024) {
            return ResultUtil.error("图片大小不能超过10MB");
        }

        try {
            // 获取项目根目录下的resources/static/img/avatar目录 (源代码目录)
            String srcPath = System.getProperty("user.dir") + "/src/main/resources/static/img/avatar/";
            File srcDir = new File(srcPath);
            if (!srcDir.exists()) {
                srcDir.mkdirs();
            }

            // 获取target/classes/static/img/avatar目录 (编译后目录)
            String targetPath = System.getProperty("user.dir") + "/target/classes/static/img/avatar/";
            File targetDir = new File(targetPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String newFilename = UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 保存文件到源代码目录
            String srcFilePath = srcPath + newFilename;
            file.transferTo(new File(srcFilePath));

            // 复制文件到target目录
            Files.copy(
                    new File(srcFilePath).toPath(),
                    new File(targetPath + newFilename).toPath(),
                    StandardCopyOption.REPLACE_EXISTING
            );

            // 返回可访问的URL路径
            String urlPath = "/img/avatar/" + newFilename;

            // 更新游客头像信息
            Visitors visitor = visitorsDao.queryById(visitorId);
            if (visitor != null) {
                visitor.setAvatar(urlPath);
                visitorsDao.update(visitor);
            }

            Map<String, String> data = new HashMap<>();
            data.put("url", urlPath);
            data.put("filename", newFilename);

            return ResultUtil.success(data);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("文件上传失败: " + e.getMessage());
        }
    }
    @Override
    public boolean resetPassword(String phoneNumber, String newPassword) {
        // 根据手机号查找游客
        Visitors visitor = visitorsDao.findVisitorById(phoneNumber);
        if (visitor == null) {
            return false;
        }

        // 加密新密码
        String encodedPassword = PasswordEncoderUtil.encode(newPassword);
        visitor.setPassword(encodedPassword);

        // 重新生成盐值
        String newSalt = PasswordEncoderUtil.generateSalt();
        visitor.setSalt(newSalt);

        // 更新修改时间
        visitor.setUpdateTime(new Date());

        // 更新数据库
        return visitorsDao.updateVisitor(visitor) > 0;
    }
}